package nl.ypmits.utils.as3.bitmap.bitmaplayers {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.PixelSnapping;
	
	/**
	 * @author davelenz
	 */
	public class BitmapLayers {
		private var _smoothing : Boolean = false;
		private var _pixelSnapping : String = PixelSnapping.NEVER;
		private var items : Array = [];
		public var _layers : Array;
		
		
		public function BitmapLayers( pixelSnapping : String = "never", smoothing : Boolean = false ) {
			this.pixelSnapping = pixelSnapping;
			this.smoothing = smoothing;
		}

		
		public function addItem( bitmapLayersItem : BitmapLayersVO ) : void
		{
			var layers : Array = [];
			var w : int = bitmapLayersItem.bitmapdata.width;
			var h : int = bitmapLayersItem.bitmapdata.height;
			for ( var i : int = 0; i < bitmapLayersItem.numLayers ; i++) 
			{
				var bm : Bitmap = new Bitmap( new BitmapData( w, h, true, 0x00000000 ), _pixelSnapping, _smoothing );
				bm.x = -(w * .5);
				bm.y = -(h * .5);
				layers.push( bm );
			}
			var n : Number = 1 / bitmapLayersItem.numLayers;
			for(i = 0; i < w ; i += bitmapLayersItem.everyPixelNum ) 
			{
				for(var j : int = 0; j < h ; j += bitmapLayersItem.everyPixelNum ) 
				{
					var c : uint = bitmapLayersItem.bitmapdata.getPixel32( i, j );
					var b : Number = bitmapLayersItem.bitmapdata.getPixel( i, j ) / 0xFFFFFF;
					for (var k : int = 0; k < layers.length ; k++) 
					{
						if( b > (k * n) && b <= ((k + 1) * n)) 
						{
							Bitmap( layers[ k ] ).bitmapData.setPixel32( i, j, c );
							break;
						} else if (b == 0) 
						{
							Bitmap( layers[ k ] ).bitmapData.setPixel32( i, j, c );
							break;
						}
					}
				}
			}
			items.push( layers );
		}
		
		
		public function get layers() : Array
		{
			return items;
		}
		
		
		public function set smoothing(smoothing : Boolean) : void
		{
			_smoothing = smoothing;
		}
		
		
		public function set pixelSnapping(pixelSnapping : String) : void
		{
			_pixelSnapping = pixelSnapping;
		}
	}
}